#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t lock;
int count = 0;

void *increment(void *arg)
{
    pthread_mutex_lock(&lock);
    count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
    count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
	count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
	count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
	pthread_mutex_unlock(&lock);
    return NULL;
}

void *increment2(void *arg)
{
    count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
    count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
	count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
	count++;
    printf("Thread %ld incremented count to %d\n", (long)arg, count);
	return NULL;
}

int main()
{
    pthread_t threads[5];
    long id;

	for(id = 0; id < 5; id++) {
        if(pthread_create(&threads[id], NULL, &increment2, (void*)id) != 0) {
            printf("Error: pthread_create() failed\n");
            exit(EXIT_FAILURE);
        }
    }

    for(id = 0; id < 5; id++) {
        pthread_join(threads[id], NULL);
    }

	printf("Press any key to continue: \n");
	getchar();

    pthread_mutex_init(&lock, NULL);

    for(id = 0; id < 5; id++) {
        if(pthread_create(&threads[id], NULL, &increment, (void*)id) != 0) {
            printf("Error: pthread_create() failed\n");
            exit(EXIT_FAILURE);
        }
    }

    for(id = 0; id < 5; id++) {
        pthread_join(threads[id], NULL);
    }

    pthread_mutex_destroy(&lock);

    return 0;
}
